package com.basic.system.service.impl;

import com.basic.common.bean.BeanCopierDsUtil;
import com.basic.common.constant.CommonDsConstant;
import com.basic.common.exception.Errors;
import com.basic.common.exception.business.ServerServiceException;
import com.basic.common.utils.DownUtils;
import com.basic.common.utils.UploadUtil;
import com.basic.member.mapper.MemberInfoMapper;
import com.basic.system.dao.mapper.*;
import com.basic.system.dao.model.SysManagement;
import com.basic.system.domain.SystemFile;
import com.basic.system.domain.SystemFileExample;
import com.basic.system.domain.bo.SysMgmtBo;
import com.basic.system.domain.vo.SMDetailVo;
import com.basic.system.domain.vo.SMIndexVo;
import com.basic.system.domain.vo.SystemFileVo;
import com.basic.system.service.SysMgmtService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SysMgmtServiceImpl implements SysMgmtService {
    //日志信息
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysManagementExMapper sysManagementExMapper;
    @Autowired
    private SysManagementMapper sysManagementMapper;
    @Autowired
    private SystemFileMapper systemFileMapper;
    @Resource
    private SystemFileExMapper systemFileExMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;

    /** 条件分页查询 */
    @Override
    public PageInfo selListByParam(SysMgmtBo bo) {
        // 分页
        PageHelper.startPage(bo.getPageNum(), bo.getPageSize());
        List<SMIndexVo> list = sysManagementExMapper.selectAllByDeptId(bo);
        return new PageInfo<>(list);
    }

    /**
     * 管理制度详细文件信息
     */
    @Override
    @Transactional
    public SMDetailVo selManagerAndFile(Long id) {
        //从数据库中获取主表信息
        SysManagement sysManagement = sysManagementMapper.selectByPrimaryKey(id);
        // 获取文件Id数组
        String[] fileIdList = sysManagement.getUrl().split(",");
        List<Long> longList = Arrays.stream(fileIdList).map(Long::valueOf).collect(Collectors.toList());
        // 封装为vo
        SMDetailVo smDetailVo = BeanCopierDsUtil.copyProperties(sysManagement, SMDetailVo.class);
        // 查询文件列表信息
        SystemFileExample example = new SystemFileExample();
        example.createCriteria().andIdIn(longList).andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED);
        List<SystemFile> fileList = systemFileMapper.selectByExample(example);
        List<SystemFileVo> fileVoList = BeanCopierDsUtil.copyPropertiesOfList(fileList, SystemFileVo.class);
        smDetailVo.setSysFileList(fileVoList);
        return smDetailVo;
    }

    /** 添加 */
    @Override
    @Transactional
    public int add(SysManagement bo) {
        try {
            // 设置创建时间
            bo.setCreateTime(new Date());
            // 根据boId查询上传人姓名
            String userName = memberInfoMapper.selectByPrimaryKey(bo.getBoId()).getUserName();
            // 根据dept_id查询部门名称
            String deptName = sysDeptMapper.selectByPrimaryKey(bo.getDeptId()).getDeptName();
            bo.setUploader(userName);
            bo.setCreateBy(userName);
            bo.setDeptName(deptName);
            //插入关联系统文件表
            sysManagementMapper.insertSelective(bo);

            String[] fileIds = bo.getUrl().split(",");
            // 输出拆分后的结果
            for (String fileId : fileIds) {
                SystemFile systemFile = new SystemFile();
                systemFile.setId(Long.valueOf(fileId));
                systemFile.setRefId(bo.getId());
                systemFileMapper.updateByPrimaryKeySelective(systemFile);
            }
            // 返回插入条数
            return sysManagementMapper.updateByPrimaryKeySelective(bo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 修改 */
    @Override
    @Transactional
    public int updById(SysManagement bo) {
        if (sysManagementMapper.updateByPrimaryKeySelective(bo) > 0){
            return 1;
        }
        throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
    }



    /** 单删 */
    @Override
    @Transactional
    public int delById(Long id) {
        if (sysManagementExMapper.delSysManagementById(id) > 0) {
            if (systemFileExMapper.delByRefId(id) > 0) {
                return 1;
            } else {
                logger.error("制度管理ID:{}相关文件删除失败(或已被删除)", id);
                throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
            }
        } else {
            logger.error("ID{}删除失败(或已被删除)", id);
            throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
        }
    }

    /** 批量删除 */
    @Override
    public int delByIds(Long[] ids) {
        // 批量删除管理制度
        if (sysManagementExMapper.delSysManagementByIds(ids) > 0){
            //在批量删除相关文件信息
            if (systemFileExMapper.delByRefIds(ids) > 0){
                return 1;
            }else {
                throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
            }
        }
        throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
    }

    /**
     * 文件下载接口
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public ResponseEntity<byte[]> download(HttpServletRequest request) {
        String fileId = request.getParameter("id");
        SystemFile systemFile = systemFileMapper.selectByPrimaryKey(Long.valueOf(fileId));
        return DownUtils.downLoad(systemFile.getUrl(), systemFile.getDescription(), request);
    }

    /**
     * 文件上传接口
     * @param files
     * @return
     */
    public String upload(List<MultipartFile> files) {
        StringBuilder fileIds = new StringBuilder();
        for (MultipartFile file : files) {
            SystemFile systemFile = new SystemFile();
            String fileName = Objects.requireNonNull(file.getOriginalFilename());
            systemFile.setType(fileName.substring(fileName.lastIndexOf(".") + 1));
            systemFile.setDescription(fileName);
            systemFile.setBusType("管理制度");
            systemFile.setCreateTime(new Date());

            String s = UploadUtil.accessoryFile(file);
            systemFile.setUrl(s);

            systemFileMapper.insertSelective(systemFile);
            fileIds.append(systemFile.getId()).append(",");
        }

        if (fileIds.length() > 0) {
            fileIds.deleteCharAt(fileIds.length() - 1);
        }
        return String.valueOf(fileIds);
    }
}
